﻿using System.Collections.Generic;
using UnityEngine;

namespace Pisces
{
	/**
	 * 单例模块容器
     * created by wangqiang
    **/
	public class SingletonModuleContainer : AbstractSingletonModule<SingletonModuleContainer>, InterfaceEntityLiftcycle
	{
		/**
		 * 注册进来的单例模块
		 */
		private List<InterfaceEntityLiftcycle> singletonModules = new List<InterfaceEntityLiftcycle>();

		public override void onInit()
		{
			base.onInit();
			
			// 注册单例
			registerSingletonModule(AssetModule.getSingleton());
			registerSingletonModule(EntityContainerModule.getSingleton());
			EntityContainerModule.getSingleton().CreateFactory = EntityCreateFactory.create;
			registerSingletonModule(SceneModule.getSingleton());
			
			registerSingletonModule(EffectModule.getSingleton());
			registerSingletonModule(NetworkModule.getSingleton());
		}

		public override void onAwake()
		{
			base.onAwake();
			
			int length = singletonModules.Count;
			for (int i = 0; i < length; i++)
			{
				this.singletonModules[i].onAwake();
			}
		}

		public override void onUpdate(float deltaTime)
		{
			base.onUpdate(deltaTime);

			int length = singletonModules.Count;
			for (int i = 0; i < length; i++)
			{
				this.singletonModules[i].onUpdate(deltaTime);
			}
		}

		public override void onDestroy()
		{
			base.onDestroy();
			
			int length = singletonModules.Count;
			for (int i = 0; i < length; i++)
			{
				this.singletonModules[i].onDestroy();
			}
		}

		/// <summary>
		/// 注册mono单例模块
		/// </summary>
		/// <param name="module"></param>
		/// <typeparam name="T"></typeparam>
		private void registerMonoSingletonModule<T>(AbstractMonoSingletonModule<T> module) where T : MonoBehaviour, InterfaceEntityLiftcycle
		{
			if (module == null)
			{
				return;
			}

			if (singletonModules.Contains((InterfaceEntityLiftcycle)module))
			{
				return;
			}
			
			singletonModules.Add((InterfaceEntityLiftcycle)module);
		}
		
		private void registerSingletonModule(InterfaceEntityLiftcycle module)
		{
			if (module == null)
			{
				return;
			}

			if (singletonModules.Contains(module))
			{
				return;
			}
			
			singletonModules.Add(module);
		}
	}
}